<?php
/**
 * Created by JetBrains PhpStorm.
 * User: duonglt
 * Date: 10/11/13
 * Time: 3:28 PM
 * To change this template use File | Settings | File Templates.
 */

class Bootstrap{
    public static function run()
    {
        self::setSystemRequirements();
        self::initAutoloader();
        self::initConfiguration();
        self::setupFramework();
//should move to log service as configuration
        self::initLogger();
        self::process();
    }
    public static function runWithoutDispath()
    {
        self::setSystemRequirements();
        self::initAutoloader();
        self::initConfiguration();
        self::setupFramework();
//should move to log service as configuration
        self::initLogger();
        Zend\Mvc\Application::init(require CORE_CONFIGURATION_DIRECTORY.'/application.config.php');
    }

    private static function setSystemRequirements()
    {
        $maxExecutionTime = 240;
        error_reporting(E_ALL ^ E_NOTICE);
        @ini_set("memory_limit", "1024M");
        @ini_set("max_execution_time", $maxExecutionTime);
        @ini_set("short_open_tag", 1);
        @ini_set("magic_quotes_gpc", 0);
        @ini_set("magic_quotes_runtime", 0);
        set_time_limit($maxExecutionTime);

        // this is for simple_dom_html
        ini_set('pcre.recursion-limit', 100000);
    }

    private static function initAutoloader()
    {
        require_once 'Zend/Loader/ClassMapAutoloader.php';
        $loader = new Zend\Loader\ClassMapAutoloader(array(
            LIB_PATH.'/Zend/autoload_classmap.php',
            LIB_PATH.'/Core/autoload_classmap.php',
//            MODEL_PATH.'/Model/autoload_classmap.php',
        ));
        $loader->register();

    }

    private static function initConfiguration()
    {
        $config = Core\Config::getSystemConfig();
        date_default_timezone_set($config->general->timezone);
    }

    private static function setupFramework()
    {
        foreach (array('TMPDIR', 'TEMP', 'TMP', 'windir', 'SystemRoot') as $key) {
            $_ENV[$key] = CORE_CACHE_DIRECTORY;
            $_SERVER[$key] = CORE_CACHE_DIRECTORY;
        }

        /*// set custom view renderer
        $pimcoreViewHelper = new Pimcore_Controller_Action_Helper_ViewRenderer();
        Zend_Controller_Action_HelperBroker::addHelper($pimcoreViewHelper);

        // set dummy timezone if no tz is specified / required for example by the logger, ...
        $defaultTimezone = @date_default_timezone_get();
        if (!$defaultTimezone) {
            date_default_timezone_set("Europe/Berlin");
        }

        // set locale data cache
        Zend_Locale_Data::setCache(Pimcore_Model_Cache::getInstance());*/
    }

    private static function initLogger()
    {
        Logger::resetLoggers();

        // try to load configuration
        $conf = Core\Config::getSystemConfig();
/*
        if ($conf) {
            //firephp logger
            if ($conf->general->firephp) {
                $writerFirebug = new Zend\Log\Writer\FirePhp();
                $loggerFirebug = new Zend\Log\Logger();
                $loggerFirebug->addWriter($writerFirebug);
                Logger::addLogger($loggerFirebug);
            }
        }*/


        if (!is_file(CORE_LOG_DEBUG)) {
            if (is_writable(dirname(CORE_LOG_DEBUG))) {
                file_put_contents(CORE_LOG_DEBUG, "AUTOCREATE\n");
            }
        }

        if (is_writable(CORE_LOG_DEBUG)) {

            // check for big logfile, empty it if it's bigger than about 200M
            if (filesize(CORE_LOG_DEBUG) > 100000000) {
                file_put_contents(CORE_LOG_DEBUG, "");
            }

            $prioMapping = array(
                "debug" => Zend\Log\Logger::DEBUG,
                "info" => Zend\Log\Logger::INFO,
                "notice" => Zend\Log\Logger::NOTICE,
                "warning" => Zend\Log\Logger::WARN,
                "error" => Zend\Log\Logger::ERR,
                "critical" => Zend\Log\Logger::CRIT,
                "alert" => Zend\Log\Logger::ALERT,
//                "emergency" => Zend\Log\Logger::EMERG
            );

            $prios = array();

            if ($conf && $conf->general->loglevel) {
                $prioConf = $conf->general->loglevel->toArray();
                if (is_array($prioConf)) {
                    foreach ($prioConf as $level => $state) {
                        if ($state) {
                            $prios[] = $prioMapping[$level];
                        }
                    }
                }
            }
            else {
                // log everything if config isn't loaded (eg. at the installer)
                foreach ($prioMapping as $p) {
                    $prios[] = $p;
                }
            }

            if (!empty($prios)) {
                $writerFile = new Zend\Log\Writer\Stream(CORE_LOG_DEBUG);
                $loggerFile = new Zend\Log\Logger();
                $loggerFile->addWriter($writerFile);

                Logger::addLogger($loggerFile);

                Logger::setPriorities($prios);
            }


                //email logger
                /*if (!empty($conf->general->logrecipient)) {
                    $user = User::getById($conf->general->logrecipient);
                    if ($user instanceof User && $user->isAdmin()) {
                        $email = $user->getEmail();
                        if (!empty($email)) {
                            $mail = Pimcore_Tool::getMail(array($email), "pimcore log notification");
                            if (!is_dir(PIMCORE_LOG_MAIL_TEMP)) {
                                mkdir(PIMCORE_LOG_MAIL_TEMP, 0755, true);
                            }
                            $tempfile = PIMCORE_LOG_MAIL_TEMP . "/log-" . uniqid() . ".log";
                            $writerEmail = new Pimcore_Log_Writer_Mail($tempfile, $mail);
                            $loggerEmail = new Zend_Log($writerEmail);
                            Logger::addLogger($loggerEmail);
                        }
                    }
                }*/
            }
        }

    private static function process()
    {

        Zend\Mvc\Application::init(require CORE_CONFIGURATION_DIRECTORY.'/application.config.php')->run();
    }


}